/*
 * @Author: 姜斌
 * @Date: 2024-05-05 15:41:10
 * @LastEditTime: 2024-05-07 09:13:00
 * @LastEditors: 姜斌
 * @Description: 配置文件
 * @FilePath: \be_quna\config\index.js
 */
const pino = require("pino");
const package = require("../package.json");
const dayjs = require("dayjs");
const os = require("node:os");
const mysql = require("mysql2");
const Redis = require("ioredis");
const pinoHttp = require("pino-http");
const mode = process.env.MODE;
module.exports = {
  setLogger: () => {
    const hooks = {
      logMethod(inputArgs, method, level) {
        if (inputArgs.length >= 2) {
          const arg1 = inputArgs.shift();
          const arg2 = inputArgs.shift();
          return method.apply(this, [arg2, arg1, inputArgs.join(" ")]);
        }
        return method.apply(this, inputArgs);
      },
    };
    const logger = pino({
      hooks,
      messageKey: "payload",
      nestedKey: "payload",
      mixin(_context, level) {
        return { level_label: logger.levels.labels[level] };
      },
      base: {
        pid: process.pid,
        hostname: os.hostname(),
        mode,
        time_transform: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        logger_version: pino.version,
      },
      transport: {
        targets: [
          {
            target: "pino-pretty",
            options: {
              destination: process.stdout.fd,
              colorize: mode !== "production",
            },
          },
          {
            target: "pino/file",
            options: {
              destination: `${process.cwd()}/log_box/project-logs/${mode}/${dayjs().format(
                "YYYY-MM-DD"
              )}.log`,
              mkdir: true,
              sync: false,
            },
          },
        ],
      },
    });
    // MySQL基础配置
    const pool = mysql.createPool({
      host: "47.94.17.177",
      user: "root",
      port: "3306",
      password: "Root@1234",
      database: "keep_activity_db",
      connectionLimit: 10000,

      // host: "127.0.0.1",
      // user: "root",
      // port: "3306",
      // password: "root",
      // database: "keep_activity_db",
      // connectionLimit: 10000,
    });
    // MySQL查询
    const query = (sql, sqlParams) => {
      return new Promise((resolve, reject) => {
        pool.getConnection((err, connection) => {
          if (!err) {
            connection.query(sql, sqlParams, function (err, results, fields) {
              if (err) {
                console.log(err);
                // sql错误日志
                global.logger.error({
                  code: 500,
                  msg: "invalid request: " + err,
                });
                reject(err);
              } else {
                console.log(results);
                resolve(results);
                connection.destroy();
              }
            });
          } else {
            console.log("conn err----", err);
            reject(err);
          }
        });
      });
    };
    // 封装事务处理函数
    const runTransaction = async (queries) => {
      let connection;
      try {
        // 从连接池获取连接
        connection = await pool.getConnection();
        await connection.beginTransaction();

        // 执行事务中的所有查询
        for (const query of queries) {
          await connection.query(query.sql, query.values);
        }

        // 如果所有查询都成功，提交事务
        await connection.commit();
        console.log("Transaction committed successfully.");
      } catch (error) {
        // 如果遇到错误，回滚事务
        if (connection) {
          await connection.rollback();
          console.error("Transaction rolled back due to error:", error);
        }
        throw error; // 重新抛出错误以便上层调用者处理
      } finally {
        // 释放连接回连接池
        if (connection) {
          connection.release();
        }
      }
    };
    // Redis配置
    const connectRedis = () => {
      const client = new Redis({
        host: "47.94.17.177", // redis地址
        port: 6379, //端口
        password: "Root@1234", //密码
        db: 1,
      });

      return new Promise((resolve, reject) => {
        client.on("connect", () => {
          console.log("Redis连接成功111");
          global.connectRedis = client;
          resolve(client);
        });

        client.on("error", (err) => {
          console.error("Redis连接失败:", err);
          reject(err);
        });
      });
    };
    // connectRedis();
    global.query = query;
    global.runTransaction = runTransaction;
    global.logger = logger;
  },
  setHttpLogger: () => {
    return pinoHttp({
      quietReqLogger: true,
      transport: {
        target: "pino-http-print",
        options: {
          destination: process.stdout.fd,
          relativeUrl: true,
          colorize: mode === "development",
          all: true,
          translateTime: true,
          showTime: mode === "development",
        },
      },
    });
  },
};
